package com.liang.maogouyuyin.ui.activity

import android.Manifest
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.View
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.activity.result.contract.ActivityResultContracts
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatActivity
import com.liang.maogouyuyin.TheBaseApplication
import com.liang.maogouyuyin.databinding.ActivityAddPetBinding
import com.liang.maogouyuyin.ui.viewmodel.PetViewModel
import com.liang.maogouyuyin.utils.DateUtil
import com.liang.maogouyuyin.utils.lzy.PermissionUtils
import com.bumptech.glide.Glide
import com.lxj.xpopup.XPopup
import com.lxj.xpopupext.listener.TimePickerListener
import com.lxj.xpopupext.popup.TimePickerPopup
import java.io.File
import java.io.FileOutputStream
import java.util.Calendar
import java.util.Date

class AddPetActivity : AppCompatActivity() {
    private lateinit var binding: ActivityAddPetBinding

    private lateinit var petViewModel: PetViewModel
    //是否设置头像
    private var isNotSetProfile = true
    private var tempUri = ""
    //true 表示为公 false 表示为母
    private var sex = true
    private var birthday = -1L
    private var arriveHome = -1L

    private val profileLauncher = registerForActivityResult(ActivityResultContracts.GetContent()) {
        it?.also {
            tempUri = it.toString()
            Glide.with(this).load(it).into(binding.addPetProfile)
            isNotSetProfile = false
        }
    }

    @RequiresApi(Build.VERSION_CODES.TIRAMISU)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        binding = ActivityAddPetBinding.inflate(layoutInflater)
        setContentView(binding.root)

        initData()
        initView()
        initClick()
    }

    private fun initData() {
        petViewModel = TheBaseApplication.getInstance().petViewModel
    }

    private fun initView() {
        binding.addPetName.addTextChangedListener(object: TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                if (s?.length == 10) {
                    Toast.makeText(this@AddPetActivity, "最多可输入10个字", Toast.LENGTH_SHORT).show()
                }
            }

            override fun afterTextChanged(s: Editable?) {}
        })

        binding.addPetName.setOnClickListener {
            if (binding.addPetName.text.length == 10)
                Toast.makeText(this@AddPetActivity, "最多可输入10个字", Toast.LENGTH_SHORT).show()
        }
    }

    @RequiresApi(Build.VERSION_CODES.TIRAMISU)
    private fun initClick() {
        binding.addPetToolBar.setNavigationOnClickListener {
            finish()
        }

        binding.addPetProfilePicker.setOnClickListener {
            PermissionUtils.tryToDoSomethingWithCheckPermissionAndCode(
                this,
                arrayOf(Manifest.permission.READ_MEDIA_IMAGES),
                2,
                "没有权限将无法获取图片"
            ) {
                profileLauncher.launch("image/*")
            }
        }

        binding.addPetSexPicker.setOnClickListener {
            XPopup.Builder(this)
                .asBottomList(
                    "性别",
                    arrayOf("公", "母")
                ) { position, text ->
                    binding.addPetSex.text = text
                    sex = position == 0
                }.show()
        }

        binding.addPetBirthdayPicker.setOnClickListener {
            val calendar = Calendar.getInstance()
            XPopup.Builder(this)
                .asCustom(TimePickerPopup(this)
                    .setDefaultDate(calendar)
                    .setDateRange(null, calendar)
                    .setTimePickerListener(object: TimePickerListener {
                        override fun onTimeChanged(date: Date?) {}

                        override fun onTimeConfirm(date: Date?, view: View?) {
                            if (arriveHome <= date!!.time && arriveHome != -1L) {
                                Toast.makeText(this@AddPetActivity, "到家时间不能小于出生时间", Toast.LENGTH_SHORT).show()
                                return
                            }
                            binding.addPetBirthday.text = DateUtil.formatTimeStamp(date.time)
                            birthday = date.time
                        }

                        override fun onCancel() {}
                    })
                ).show()
        }

        binding.addPetArriveHomePicker.setOnClickListener {
            val calendar = Calendar.getInstance()
            XPopup.Builder(this)
                .asCustom(TimePickerPopup(this)
                    .setDefaultDate(calendar)
                    .setDateRange(null, calendar)
                    .setTimePickerListener(object: TimePickerListener {
                        override fun onTimeChanged(date: Date?) {}

                        override fun onTimeConfirm(date: Date?, view: View?) {
                            if (birthday >= date!!.time) {
                                Toast.makeText(this@AddPetActivity, "到家时间不能小于出生时间", Toast.LENGTH_SHORT).show()
                                return
                            }
                            binding.addPetArriveHome.text = DateUtil.formatTimeStamp(date.time)
                            arriveHome = date.time
                        }

                        override fun onCancel() {}
                    })
                ).show()
        }

        binding.addPetSave.setOnClickListener {
            if (isNotSetProfile) {
                Toast.makeText(this, "请设置宠物头像", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            } else if (binding.addPetName.text.isNullOrEmpty()) {
                Toast.makeText(this, "请输入宠物名称", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            } else if (binding.addPetSex.text.contentEquals("选择")) {
                Toast.makeText(this, "请选择宠物性别", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            } else if (birthday == -1L) {
                Toast.makeText(this, "请选择出生时间", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            } else if (arriveHome == -1L) {
                Toast.makeText(this, "请选择到家时间", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }

            petViewModel.savePet(
                saveImage(),
                binding.addPetName.text.toString(),
                sex,
                birthday,
                arriveHome
            )

            finish()
        }
    }

    private fun saveImage(): String {
        val inputStream = contentResolver.openInputStream(Uri.parse(tempUri))

        val file = File(filesDir, tempUri.hashCode().toString())
        FileOutputStream(file).use {
            outputStream -> inputStream?.copyTo(outputStream)
        }

        inputStream?.close()
        return file.absolutePath
    }
}